//package vmmjava;

import java.io.*;
import java.net.*;
import org.jdom.Document;
import org.jdom.JDOMException;

public class VMMClient {

  private static String file;
  private static String host;
  private static int port;

  VMMClient(String file, String host, String port) {
    this.file = file;
    this.host = host;
    this.port = Integer.parseInt(port);
  }

  public static void main(String args[]) {
    if(args.length != 3) System.out.println("Use: java VMMClient file.xml address port");
    else {
      try {
        VMMClient client = new VMMClient(args[0], args[1], args[2]);
        VMMClient.run();
      } catch(SecurityException se) {
        System.out.println("Error: operation not allowed!");
        System.out.println(se.getMessage());
      } catch(Exception ex) {
        System.out.println(ex.getMessage());
      }
    }
  }
  
  // Sends the file passed as a parameter to the server
  public static void run() {
    try {
      System.out.println("Trying to connect to server "+ host +" on port "+ port +"...");
      Socket server = new Socket(host, port);
      System.out.println("Connected to server!");

      VMManagerOutputStream serverOut = new VMManagerOutputStream(server);
      VMManagerInputStream  serverIn  = new VMManagerInputStream(server);
      BufferedReader        fileIn    = new BufferedReader(new FileReader(file));
     
      String line; 
      StringBuffer cmd = new StringBuffer();
      // Read file into a string
      while((line = fileIn.readLine()) != null) cmd.append(line+"\n");
      // Write file into the output stream (server socket)
      serverOut.println(cmd.toString());
      // Get response
      Document xml      = serverIn.buildXMLfromRequest();
      String xml_string = MyXMLOutputter.outputDocument(xml);
      System.out.println("VMManager says...");
      System.out.println(xml_string);
      System.out.println("******************************");
      // Close connection
      serverOut.close();
      serverIn.close();
      server.close();

    } catch(FileNotFoundException fnfe) {
      System.out.println("Error: file not found!");
    } catch(IOException ioe) {
      System.out.println("I/O Error!"+ ioe.getMessage());
    } catch(JDOMException jde) {
      System.out.println("JDOM error: "+ jde.getMessage());
    }
  }
}
